// 关闭蓝牙
export function closeBluetoothAdapter() {
  return new Promise((resolve, reject) => {
    uni.closeBluetoothAdapter({
      success(res) {
        console.log('已关闭蓝牙模块', res)
        resolve(res)
      },
      fail(err) {
        console.log('已关闭蓝牙模块-失败', err)
        reject(err)
      },
    })
  })
}

/** 断开低功耗蓝牙连接 */
export function closeBLEConnection(deviceId: string) {
  return new Promise((resolve, reject) => {
    uni.closeBLEConnection({
      deviceId,
      success(res) {
        console.log('已断开低功耗蓝牙连接')
        resolve(true)
      },
      fail(res) {
        resolve(true)
      },
    })
  })
}

/** 获取蓝牙设备列表 */
export function getBluetoothDevicesList() {
  return new Promise((resolve, reject) => {
    openBluetooth()
      .then(() => getBluetoothAdapterState())
      .then(() => searchBluetooth())
      .then(() => getBluetoothDevices())
      .then((res: UniApp.GetBluetoothDevicesSuccess) => {
        console.log('蓝牙列表', res)

        if (res && res.devices) {
          resolve(res.devices)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}

/** 获取本机蓝牙适配器状态 */
export function getBluetoothAdapterState() {
  return new Promise((resolve, reject) => {
    uni.getBluetoothAdapterState({
      success(res) {
        console.log('蓝牙状态', res)
        if (res.available) {
          if (res.discovering) {
            stopSearchBluetooth()
          } else {
            resolve(res)
          }
        } else {
          uni.showModal({
            title: '提示',
            content: '本机蓝牙不可用',
            showCancel: false,
          })
          reject(res)
        }
      },
      fail(err) {
        console.log('蓝牙状态-err', err)
        // console.log("blueTooth error= startBluetoothDevicesDiscovery", err);
        reject(err)
      },
    })
  })
}

/** 搜索蓝牙设备 */
export function searchBluetooth() {
  return new Promise((resolve, reject) => {
    uni.startBluetoothDevicesDiscovery({
      success: (res) => {
        console.log('searchBluetooth', res)

        setTimeout(() => {
          resolve(res)
        }, 5000)
      },
      fail: (err) => {
        console.log('searchBluetooth-err', err)

        // console.log("blueTooth error= startBluetoothDevicesDiscovery", err);
        reject(err)
      },
    })
  })
}

/** 获取搜索到的蓝牙设备 */
export function getBluetoothDevices() {
  return new Promise((resolve, reject) => {
    uni.getBluetoothDevices({
      success: (res) => {
        console.log('getBluetoothDevices', res)

        resolve(res)
      },
      fail: (err) => {
        console.log('getBluetoothDevices-err', err)

        // console.log("blueTooth error= getBluetoothDevices", res);
        reject(err)
      },
    })
  })
}

// 初始化蓝牙连接
export function openBluetooth() {
  return new Promise((resolve, reject) => {
    uni.openBluetoothAdapter({
      success: (res) => {
        console.log('蓝牙模块初始成功', res)
        resolve(res)
      },
      fail: (err) => {
        // console.log("blueTooth error= openBluetoothAdapter", res);
        console.log('蓝牙模块初始化失败', err)
        reject(err)
      },
    })
  })
}

/** 停止搜索蓝牙 */
export function stopSearchBluetooth() {
  uni.stopBluetoothDevicesDiscovery({
    complete: (res) => {
      // console.log("stopBluetoothDevicesDiscovery", res);
    },
  })
}

/** 连接低功耗蓝牙 */
export function connectBLEDevice(deviceId: string) {
  return new Promise((resolve, reject) => {
    uni.createBLEConnection({
      deviceId,
      success: (res) => {
        console.log('createBLEConnection success', res)
        resolve(deviceId)
      },
      fail: (err) => {
        console.log('createBLEConnection fail', err)
        reject(err)
      },
    })
  })
}

/** 获取蓝牙设备所有服务 */
export function getBLEDeviceServices(deviceId: string): Promise<{
  msg: string
  deviceId: string
  serviceId: string
}> {
  return new Promise((resolve, reject) => {
    uni.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        console.log('getBLEDeviceServices', res)
        for (let i = 0; i < res.services.length; i++) {
          const item = res.services[i]
          if (item.isPrimary) {
            // this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
            resolve({
              msg: '获取蓝牙设备服务成功',
              deviceId,
              serviceId: item.uuid,
            })
            return
          }
        }
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

/** 获取蓝牙设备某个服务中的特征值列表 */
export function getBLEDeviceCharacteristics({
  deviceId,
  serviceId,
}: {
  deviceId: string
  serviceId: string
}): Promise<{
  msg: string
  deviceId: string
  serviceId: string
  characteristicId: string
}> {
  return new Promise((resolve, reject) => {
    uni.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        // console.log("getBLEDeviceCharacteristics success", res.characteristics);
        // 这里会存在特征值是支持write，写入成功但是没有任何反应的情况
        // 只能一个个去试
        for (let i = 0; i < res.characteristics.length; i++) {
          const item = res.characteristics[i]
          if (item.properties.write) {
            resolve({
              msg: '获取蓝牙设备指定服务中所有特征值成功',
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
            break
          }
        }
        reject({
          msg: '该设备不可用',
        })
      },
      fail(err) {
        // console.error("getBLEDeviceCharacteristics", res);
        reject(err)
      },
    })
  })
}

/** 连接蓝牙 */
export function connectBluetoothDevice(
  deviceId: string,
): Promise<{ msg: string; deviceId: string; serviceId: string; characteristicId: string }> {
  return new Promise((resolve, reject) => {
    stopSearchBluetooth()
    connectBLEDevice(deviceId)
      .then(() => getBLEDeviceServices(deviceId))
      .then((res) => {
        return getBLEDeviceCharacteristics({
          deviceId: res.deviceId,
          serviceId: res.serviceId,
        })
      })
      .then((res) => {
        console.log('ppppp', res)
        resolve(res)
      })
      .catch((e) => {
        reject(e)
      })
  })
}

// 打印
export function bluetoothPrint(params: UniNamespace.WriteBLECharacteristicValueOptions) {
  return new Promise((resolve, reject) => {
    uni.writeBLECharacteristicValue({
      ...params,
      success(res) {
        console.log('writeBLECharacteristicValue success', res)
        resolve('success')
      },
      fail(res) {
        resolve('fail')
        console.log('writeBLECharacteristicValue fail', res)
      },
    })
  })
}
